// 智能瓷砖监控系统 API 服务
import axios from 'axios'

// 创建 axios 实例
const api = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || 'http://localhost:3000/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 可以在这里添加认证 token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API 请求错误:', error)
    return Promise.reject(error)
  }
)

/**
 * 智能瓷砖监控 API 服务类
 */
class SmartTileApiService {
  /**
   * 获取系统概况统计数据
   * @returns {Promise} 统计数据
   */
  async getSystemStats() {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockSystemStats()
  }

  /**
   * 获取压力热图数据
   * @param {Object} params - 查询参数
   * @param {string} params.area - 区域选择 (all, A, B, C)
   * @param {string} params.timeRange - 时间范围
   * @returns {Promise} 热图数据
   */
  // eslint-disable-next-line no-unused-vars
  async getHeatmapData(params = {}) {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockHeatmapData()
  }

  /**
   * 获取趋势图数据
   * @param {Object} params - 查询参数
   * @param {string} params.timeRange - 时间范围 (today, yesterday, week, month)
   * @returns {Promise} 趋势数据
   */
  // eslint-disable-next-line no-unused-vars
  async getTrendData(params = {}) {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockTrendData()
  }

  /**
   * 获取区域对比数据
   * @returns {Promise} 对比数据
   */
  async getComparisonData() {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockComparisonData()
  }

  /**
   * 获取异常列表数据
   * @param {Object} params - 查询参数
   * @param {number} params.page - 页码
   * @param {number} params.pageSize - 每页数量
   * @param {string} params.severity - 严重程度筛选
   * @returns {Promise} 异常数据
   */
  // eslint-disable-next-line no-unused-vars
  async getExceptionData(params = {}) {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockExceptionData()
  }

  /**
   * 获取系统健康评分
   * @returns {Promise} 健康评分数据
   */
  async getHealthScore() {
    // 直接返回模拟数据，避免API连接错误
    return this.getMockHealthScore()
  }

  /**
   * 刷新所有数据
   * @returns {Promise} 刷新结果
   */
  async refreshAllData() {
    try {
      return await api.post('/system/refresh')
    } catch (error) {
      console.error('刷新数据失败:', error)
      throw error
    }
  }

  /**
   * 导出报告
   * @param {Object} params - 导出参数
   * @param {string} params.format - 导出格式 (pdf, excel)
   * @param {string} params.timeRange - 时间范围
   * @returns {Promise} 导出结果
   */
  async exportReport(params = {}) {
    try {
      return await api.post('/reports/export', params, {
        responseType: 'blob'
      })
    } catch (error) {
      console.error('导出报告失败:', error)
      throw error
    }
  }

  /**
   * 获取真实传感器数据
   * 读取本地sensor_data.json文件并转换为热图格式
   * @returns {Promise} 传感器数据
   */
  async getRealSensorData() {
    try {
      // 读取本地的sensor_data.json文件
       const response = await fetch('/sensor_data.json?t=' + Date.now())
      if (!response.ok) {
        throw new Error('无法读取传感器数据文件')
      }
      const sensorData = await response.json()
      
      // 获取最新的数据记录
      const latestData = sensorData.data && sensorData.data.length > 0 
        ? sensorData.data[sensorData.data.length - 1] 
        : null
      
      if (!latestData || !latestData.tiles || !latestData.tiles.data) {
        throw new Error('传感器数据格式不正确')
      }
      
      // 将21个传感器数据转换为3x7的热图格式
      const tilesData = latestData.tiles.data
      const heatmapData = this.convertToHeatmapFormat(tilesData)
      
      return {
        success: true,
        data: {
          heatmap: heatmapData,
          statistics: {
            total: tilesData.length,
            normal: tilesData.filter(p => p < 100).length,
            warning: tilesData.filter(p => p >= 100 && p < 200).length,
            critical: tilesData.filter(p => p >= 200).length,
            avgPressure: (tilesData.reduce((sum, p) => sum + p, 0) / tilesData.length).toFixed(1),
            maxPressure: Math.max(...tilesData),
            minPressure: Math.min(...tilesData)
          },
          metadata: {
            updateTime: latestData.pc_timestamp || new Date().toISOString(),
            dataSource: 'real_sensor',
            samplingRate: '1Hz',
            coverage: '100%'
          }
        }
      }
    } catch (error) {
      console.error('获取真实传感器数据失败:', error)
      // 降级到模拟数据
      return this.getMockHeatmapData()
    }
  }

  /**
   * 将21个传感器数据转换为3x7的热图格式
   * @param {Array} tilesData - 21个传感器的压力值数组
   * @returns {Array} 3x7的热图数据
   */
  convertToHeatmapFormat(tilesData) {
    const rows = 3
    const cols = 7
    const heatmapData = []
    
    for (let row = 0; row < rows; row++) {
      const rowData = []
      for (let col = 0; col < cols; col++) {
        const index = row * cols + col
        const pressure = index < tilesData.length ? tilesData[index] : 0
        
        // 确定压力等级（基于300的最大值）
        let level = 'normal'
        if (pressure >= 200) level = 'critical'
        else if (pressure >= 100) level = 'warning'
        
        rowData.push({
          x: col + 1,
          y: row + 1,
          pressure: pressure.toString(),
          level,
          position: `区域${String.fromCharCode(65 + Math.floor(col/3))}-${col + 1}-${row + 1}`,
          timestamp: new Date().toISOString(),
          deviceId: `TILE_${(col + 1).toString().padStart(2, '0')}_${(row + 1).toString().padStart(2, '0')}`,
          status: pressure > 0 ? 'active' : 'inactive'
        })
      }
      heatmapData.push(rowData)
    }
    
    return heatmapData
  }

  // ========== 模拟数据方法 ==========

  /**
   * 生成动态系统统计数据
   * 模拟真实的监控环境，数据会根据时间和随机因素变化
   * 每秒都会产生不同的数据
   */
  getMockSystemStats() {
    const now = new Date()
    const hour = now.getHours()
    const minute = now.getMinutes()
    const second = now.getSeconds()
    const millisecond = now.getMilliseconds()
    
    // 创建基于时间戳的种子，确保每秒都不同
    const timeBasedSeed = hour * 3600 + minute * 60 + second + millisecond / 1000
    
    // 根据时间模拟不同的系统状态
    const isBusinessHour = hour >= 8 && hour <= 18
    const isNightTime = hour >= 22 || hour <= 6
    
    // 基础设备数量
    const totalDevices = 192
    
    // 基于时间戳的伪随机数生成器，确保每秒都不同
    const seededRandom = (seed, index = 0) => {
      const x = Math.sin(seed + index) * 10000
      return x - Math.floor(x)
    }
    
    // 动态在线设备数（工作时间更多设备在线）
    let onlineBase = isBusinessHour ? 185 : (isNightTime ? 178 : 182)
    // 添加秒级波动
    const secondlyFluctuation = Math.sin(timeBasedSeed * 0.1) * 2
    const onlineVariation = Math.floor(seededRandom(timeBasedSeed, 1) * 8) - 4 + secondlyFluctuation
    const onlineDevices = Math.floor(Math.max(170, Math.min(totalDevices, onlineBase + onlineVariation)))
    
    // 动态异常信号数量（夜间可能更多异常）
    const abnormalBase = isNightTime ? 5 : (isBusinessHour ? 2 : 3)
    // 每秒微小变化
    const abnormalFluctuation = Math.sin(timeBasedSeed * 0.05) * 1.5
    const abnormalVariation = Math.floor(seededRandom(timeBasedSeed, 2) * 4) + abnormalFluctuation
    const abnormalSignals = Math.floor(Math.max(0, abnormalBase + abnormalVariation))
    
    // 动态平均压力值（根据时间和设备状态变化）
    const pressureBase = 2.5 + (hour / 24) * 1.5 // 随时间缓慢变化
    // 每秒压力波动
    const pressureWave = Math.sin(timeBasedSeed * 0.02) * 0.3
    const pressureNoise = (seededRandom(timeBasedSeed, 3) - 0.5) * 0.8 // 随机噪声
    const averagePressure = Math.max(1.0, Math.min(5.0, pressureBase + pressureNoise + pressureWave))
    
    // 动态信号总量（工作时间更多信号）
    const signalBase = isBusinessHour ? 28000 : (isNightTime ? 15000 : 22000)
    // 每秒增长模拟
    const signalIncrement = second * 5 + Math.floor(millisecond / 100) // 每秒增加约5个信号
    const signalVariation = Math.floor(seededRandom(timeBasedSeed, 4) * 5000) - 2500
    const todaySignals = Math.max(10000, signalBase + signalVariation + (minute * 30) + signalIncrement)
    
    // 动态趋势计算
    const calculateTrend = (current, base) => {
      const change = ((current - base) / base * 100)
      return {
        type: change >= 0 ? 'positive' : 'negative',
        value: `${Math.abs(change).toFixed(1)}%`
      }
    }
    
    // 系统状态判断
    let systemStatus = 'normal'
    let statusText = '运行正常'
    
    if (abnormalSignals > 8) {
      systemStatus = 'critical'
      statusText = '严重异常'
    } else if (abnormalSignals > 5 || onlineDevices < 175) {
      systemStatus = 'warning'
      statusText = '需要关注'
    } else if (onlineDevices < 180) {
      systemStatus = 'caution'
      statusText = '轻微异常'
    }
    
    return {
      success: true,
      data: {
        onlineTiles: {
          value: onlineDevices,
          unit: '块',
          trend: calculateTrend(onlineDevices, 185)
        },
        abnormalSignals: {
          value: abnormalSignals,
          unit: '处',
          trend: calculateTrend(abnormalSignals, 3)
        },
        averagePressure: {
          value: parseFloat(averagePressure.toFixed(1)),
          unit: 'kPa',
          trend: calculateTrend(averagePressure, 2.8)
        },
        todaySignals: {
          value: todaySignals,
          unit: '个',
          trend: calculateTrend(todaySignals, 25000)
        },
        systemStatus: {
          status: systemStatus,
          text: statusText,
          onlineDevices: `${onlineDevices}/${totalDevices}`,
          lastUpdate: now.toLocaleString('zh-CN'),
          uptime: this.generateUptime(),
          networkLatency: this.generateNetworkLatency()
        }
      }
    }
  }

  /**
   * 生成动态热图数据
   * 模拟真实的压力分布，包含热点区域、边缘效应和时间变化
   * 每秒都会产生不同的压力分布
   */
  getMockHeatmapData() {
    const now = new Date()
    const hour = now.getHours()
    const minute = now.getMinutes()
    const second = now.getSeconds()
    const millisecond = now.getMilliseconds()
    
    // 创建基于时间戳的种子
    const timeBasedSeed = hour * 3600 + minute * 60 + second + millisecond / 1000
    
    // 基于时间戳的伪随机数生成器
    const seededRandom = (seed, index = 0) => {
      const x = Math.sin(seed + index) * 10000
      return x - Math.floor(x)
    }
    
    // 时间因子影响整体压力水平（每秒都在变化）
    const timeFactor = 1 + 0.3 * Math.sin((hour + minute/60 + second/3600) * Math.PI / 12)
    // 添加秒级波动
    const secondlyWave = 1 + 0.1 * Math.sin(timeBasedSeed * 0.01)
    
    // 创建几个热点中心（每秒强度都在变化）
    const hotspots = [
      { 
        x: 3, 
        y: 3, 
        intensity: 1.5 + seededRandom(timeBasedSeed, 10) * 0.5 + Math.sin(timeBasedSeed * 0.02) * 0.2
      },
      { 
        x: 7, 
        y: 6, 
        intensity: 1.2 + seededRandom(timeBasedSeed, 11) * 0.8 + Math.sin(timeBasedSeed * 0.03) * 0.3
      },
      { 
        x: 5, 
        y: 8, 
        intensity: 1.0 + seededRandom(timeBasedSeed, 12) * 1.0 + Math.sin(timeBasedSeed * 0.025) * 0.4
      }
    ]
    
    const data = []
    for (let y = 1; y <= 10; y++) {
      const row = []
      for (let x = 1; x <= 10; x++) {
        // 基础压力值（边缘较低，中心较高）
        const centerDistance = Math.sqrt(Math.pow(x - 5.5, 2) + Math.pow(y - 5.5, 2))
        let basePressure = 2.0 + (4 - centerDistance) * 0.2
        
        // 热点影响
        hotspots.forEach(hotspot => {
          const distance = Math.sqrt(Math.pow(x - hotspot.x, 2) + Math.pow(y - hotspot.y, 2))
          const influence = hotspot.intensity * Math.exp(-distance * 0.5)
          basePressure += influence
        })
        
        // 添加时间变化和随机噪声（每秒都在变化）
        const timeVariation = 0.3 * Math.sin((x + y + hour + second/60) * 0.5)
        const secondlyVariation = 0.2 * Math.sin((x * y + timeBasedSeed) * 0.1)
        const randomNoise = (seededRandom(timeBasedSeed, x * 10 + y) - 0.5) * 0.6
        const pressure = Math.max(0.5, basePressure * timeFactor * secondlyWave + timeVariation + secondlyVariation + randomNoise)
        
        // 确定压力等级
        let level = 'normal'
        if (pressure > 5.5) level = 'critical'
        else if (pressure > 3.8) level = 'warning'
        
        // 模拟设备状态
        const deviceStatus = this.generateDeviceStatus(pressure)
        
        row.push({
          x,
          y,
          pressure: pressure.toFixed(1),
          level,
          position: `区域${String.fromCharCode(65 + Math.floor((x-1)/3))}-${x}-${y}`,
          timestamp: new Date().toISOString(),
          deviceId: `TILE_${x.toString().padStart(2, '0')}_${y.toString().padStart(2, '0')}`,
          temperature: (22 + seededRandom(timeBasedSeed, x * 20 + y) * 8 + Math.sin(timeBasedSeed * 0.005) * 1).toFixed(1), // 温度 22-30°C，每秒微变
          humidity: (45 + seededRandom(timeBasedSeed, x * 30 + y) * 20 + Math.sin(timeBasedSeed * 0.003) * 2).toFixed(1), // 湿度 45-65%，每秒微变
          batteryLevel: Math.floor(85 + seededRandom(timeBasedSeed, x * 40 + y) * 15), // 电池 85-100%
          signalStrength: Math.floor(70 + seededRandom(timeBasedSeed, x * 50 + y) * 30 + Math.sin(timeBasedSeed * 0.008) * 5), // 信号强度 70-100%，每秒波动
          status: deviceStatus,
          lastMaintenance: this.generateLastMaintenance(),
          alertCount: level === 'critical' ? Math.floor(Math.random() * 5) + 1 : 0
        })
      }
      data.push(row)
    }
    
    // 计算统计信息
    const allPoints = data.flat()
    const stats = {
      total: allPoints.length,
      normal: allPoints.filter(p => p.level === 'normal').length,
      warning: allPoints.filter(p => p.level === 'warning').length,
      critical: allPoints.filter(p => p.level === 'critical').length,
      avgPressure: (allPoints.reduce((sum, p) => sum + parseFloat(p.pressure), 0) / allPoints.length).toFixed(2),
      maxPressure: Math.max(...allPoints.map(p => parseFloat(p.pressure))).toFixed(1),
      minPressure: Math.min(...allPoints.map(p => parseFloat(p.pressure))).toFixed(1)
    }
    
    return {
      success: true,
      data: {
        heatmap: data,
        statistics: stats,
        legend: {
          normal: { min: 0, max: 3.8, color: '#52C41A', label: '正常' },
          warning: { min: 3.8, max: 5.5, color: '#FAAD14', label: '警告' },
          critical: { min: 5.5, max: 8, color: '#FF4D4F', label: '严重' }
        },
        metadata: {
          updateTime: now.toISOString(),
          dataSource: 'simulation',
          samplingRate: '1Hz',
          coverage: '100%'
        }
      }
    }
  }

  /**
   * 生成动态趋势数据
   * 模拟24小时的系统运行趋势，包含周期性变化和突发事件
   * 每秒都会产生不同的趋势数据
   */
  getMockTrendData() {
    const now = new Date()
    const currentHour = now.getHours()
    const currentMinute = now.getMinutes()
    const currentSecond = now.getSeconds()
    const currentMillisecond = now.getMilliseconds()
    const hours = []
    
    // 创建基于时间戳的种子
    const timeBasedSeed = currentHour * 3600 + currentMinute * 60 + currentSecond + currentMillisecond / 1000
    
    // 基于时间戳的伪随机数生成器
    const seededRandom = (seed, index = 0) => {
      const x = Math.sin(seed + index) * 10000
      return x - Math.floor(x)
    }
    
    // 生成过去24小时的数据
    for (let i = 0; i < 24; i++) {
      const hour = (currentHour - 23 + i + 24) % 24
      const timeDate = new Date(now.getTime() - (23 - i) * 60 * 60 * 1000)
      
      // 模拟日常周期：工作时间压力高，夜间压力低
      const dailyCycle = 2.5 + 1.2 * Math.sin((hour - 6) * Math.PI / 12)
      
      // 添加每秒变化的波动
      const secondlyWave = 0.2 * Math.sin((timeBasedSeed + i * 100) * 0.01)
      const randomVariation = (seededRandom(timeBasedSeed, i * 10) - 0.5) * 0.8
      const suddenEvent = seededRandom(timeBasedSeed, i * 20) < 0.05 ? (seededRandom(timeBasedSeed, i * 30) - 0.5) * 2 : 0 // 5%概率突发事件
      
      const pressure = Math.max(1.0, Math.min(6.0, dailyCycle + randomVariation + suddenEvent + secondlyWave))
      
      // 在线设备数量（工作时间更多）+ 每秒波动
      const onlineBase = hour >= 8 && hour <= 18 ? 185 : (hour >= 22 || hour <= 6 ? 178 : 182)
      const onlineVariation = Math.floor(seededRandom(timeBasedSeed, i * 40) * 8) - 4
      const onlineFluctuation = Math.sin((timeBasedSeed + i * 50) * 0.02) * 2
      const online = Math.floor(Math.max(170, Math.min(192, onlineBase + onlineVariation + onlineFluctuation)))
      
      // 告警数量（压力高时告警多）+ 每秒变化
      const alertProbability = Math.max(0, (pressure - 3.5) / 2.5)
      const alertFluctuation = Math.sin((timeBasedSeed + i * 60) * 0.03) * 1
      const alerts = Math.max(0, Math.floor(alertProbability * 8 + seededRandom(timeBasedSeed, i * 70) * 3 + alertFluctuation))
      
      // 数据吞吐量（工作时间更高）+ 每秒波动
      const throughputBase = hour >= 8 && hour <= 18 ? 1200 : (hour >= 22 || hour <= 6 ? 600 : 900)
      const throughputFluctuation = Math.sin((timeBasedSeed + i * 80) * 0.015) * 50
      const throughput = Math.floor(throughputBase + Math.floor(seededRandom(timeBasedSeed, i * 90) * 300) + throughputFluctuation)
      
      // 响应时间（压力高时响应慢）+ 每秒波动
      const responseTimeFluctuation = Math.sin((timeBasedSeed + i * 100) * 0.025) * 10
      const responseTime = 50 + pressure * 20 + seededRandom(timeBasedSeed, i * 110) * 30 + responseTimeFluctuation
      
      // 系统负载 + 每秒波动
      const loadFluctuation = Math.sin((timeBasedSeed + i * 120) * 0.02) * 5
      const systemLoad = Math.min(100, 30 + pressure * 15 + seededRandom(timeBasedSeed, i * 130) * 20 + loadFluctuation)
      
      hours.push({
        time: `${hour.toString().padStart(2, '0')}:00`,
        pressure: parseFloat(pressure.toFixed(1)),
        alerts,
        online,
        throughput,
        responseTime: parseFloat(responseTime.toFixed(1)),
        systemLoad: parseFloat(systemLoad.toFixed(1)),
        networkLatency: parseFloat((10 + seededRandom(timeBasedSeed, i * 140) * 20 + Math.sin((timeBasedSeed + i * 150) * 0.03) * 3).toFixed(1)),
        cpuUsage: parseFloat((20 + pressure * 10 + seededRandom(timeBasedSeed, i * 160) * 15 + Math.sin((timeBasedSeed + i * 170) * 0.02) * 5).toFixed(1)),
        memoryUsage: parseFloat((40 + seededRandom(timeBasedSeed, i * 180) * 30 + Math.sin((timeBasedSeed + i * 190) * 0.015) * 3).toFixed(1)),
        timestamp: timeDate.toISOString(),
        events: this.generateHourlyEvents(pressure, alerts)
      })
    }
    
    // 计算统计摘要
    const summary = {
      avgPressure: parseFloat((hours.reduce((sum, h) => sum + h.pressure, 0) / hours.length).toFixed(2)),
      totalAlerts: hours.reduce((sum, h) => sum + h.alerts, 0),
      avgOnline: Math.round(hours.reduce((sum, h) => sum + h.online, 0) / hours.length),
      maxPressure: Math.max(...hours.map(h => h.pressure)),
      minPressure: Math.min(...hours.map(h => h.pressure)),
      avgResponseTime: parseFloat((hours.reduce((sum, h) => sum + h.responseTime, 0) / hours.length).toFixed(1)),
      avgSystemLoad: parseFloat((hours.reduce((sum, h) => sum + h.systemLoad, 0) / hours.length).toFixed(1)),
      peakHour: hours.reduce((max, h, i) => h.pressure > hours[max].pressure ? i : max, 0),
      quietHour: hours.reduce((min, h, i) => h.pressure < hours[min].pressure ? i : min, 0)
    }
    
    return {
      success: true,
      data: {
        trend: hours,
        summary,
        analysis: {
          trend: this.analyzeTrend(hours),
          recommendations: this.generateRecommendations(summary),
          forecast: this.generateForecast(hours)
        },
        metadata: {
          timeRange: '24h',
          dataPoints: hours.length,
          updateFrequency: '1h',
          lastUpdate: now.toISOString()
        }
      }
    }
  }

  /**
   * 生成动态区域对比数据
   * 模拟不同区域的实时状态对比
   */
  getMockComparisonData() {
    const now = new Date()
    const hour = now.getHours()
    
    // 不同区域的基础特性
    const areaConfigs = [
      { 
        name: '区域A', 
        baseLoad: 0.7, 
        stability: 0.8, 
        deviceCount: 64,
        description: '主要生产区域，设备密度高'
      },
      { 
        name: '区域B', 
        baseLoad: 0.9, 
        stability: 0.6, 
        deviceCount: 64,
        description: '重载作业区域，压力波动大'
      },
      { 
        name: '区域C', 
        baseLoad: 0.5, 
        stability: 0.9, 
        deviceCount: 64,
        description: '辅助区域，运行稳定'
      }
    ]
    
    const areas = areaConfigs.map(config => {
      // 根据时间和区域特性计算动态数据
      const timeFactor = 1 + 0.2 * Math.sin((hour - 8) * Math.PI / 10)
      const loadFactor = config.baseLoad * timeFactor
      
      // 计算各状态设备数量
      const totalDevices = config.deviceCount
      const criticalCount = Math.floor(totalDevices * (1 - config.stability) * loadFactor * (0.5 + Math.random() * 0.5))
      const warningCount = Math.floor(totalDevices * 0.15 * loadFactor + Math.random() * 8)
      const normalCount = totalDevices - criticalCount - warningCount
      
      // 计算平均压力
      const avgPressure = 2.0 + loadFactor * 2.5 + (Math.random() - 0.5) * 0.8
      
      // 计算性能指标
      const efficiency = Math.max(60, 100 - criticalCount * 5 - warningCount * 2 + Math.random() * 10)
      const uptime = Math.max(85, 100 - criticalCount * 2 - warningCount * 0.5)
      
      return {
        area: config.name,
        normal: Math.max(0, normalCount),
        warning: warningCount,
        critical: criticalCount,
        totalDevices,
        avgPressure: parseFloat(avgPressure.toFixed(1)),
        efficiency: parseFloat(efficiency.toFixed(1)),
        uptime: parseFloat(uptime.toFixed(1)),
        description: config.description,
        status: criticalCount > 5 ? 'critical' : (warningCount > 10 ? 'warning' : 'normal'),
        lastIncident: this.generateLastIncident(),
        maintenanceSchedule: this.generateMaintenanceSchedule(),
        energyConsumption: parseFloat((50 + loadFactor * 30 + Math.random() * 20).toFixed(1)),
        dataQuality: parseFloat((85 + Math.random() * 15).toFixed(1)),
        alerts24h: criticalCount * 3 + warningCount + Math.floor(Math.random() * 5),
        trends: {
          pressure: this.generateAreaTrend(),
          efficiency: this.generateAreaTrend(),
          alerts: this.generateAreaTrend()
        }
      }
    })
    
    // 计算整体统计
    const overallStats = {
      totalDevices: areas.reduce((sum, area) => sum + area.totalDevices, 0),
      totalNormal: areas.reduce((sum, area) => sum + area.normal, 0),
      totalWarning: areas.reduce((sum, area) => sum + area.warning, 0),
      totalCritical: areas.reduce((sum, area) => sum + area.critical, 0),
      avgEfficiency: parseFloat((areas.reduce((sum, area) => sum + area.efficiency, 0) / areas.length).toFixed(1)),
      avgUptime: parseFloat((areas.reduce((sum, area) => sum + area.uptime, 0) / areas.length).toFixed(1))
    }
    
    return {
      success: true,
      data: {
        areas,
        overallStats,
        comparison: {
          bestPerforming: areas.reduce((best, area) => area.efficiency > best.efficiency ? area : best),
          worstPerforming: areas.reduce((worst, area) => area.efficiency < worst.efficiency ? area : worst),
          mostStable: areas.reduce((stable, area) => area.critical < stable.critical ? area : stable),
          recommendations: this.generateAreaRecommendations(areas)
        },
        metadata: {
          updateTime: now.toISOString(),
          comparisonPeriod: '24h',
          dataAccuracy: '95%'
        }
      }
    }
  }

  /**
   * 生成动态异常数据
   * 模拟实时的异常事件列表
   */
  getMockExceptionData() {
    const now = new Date()
    const exceptions = []
    
    // 异常类型定义
    const exceptionTypes = [
      {
        type: 'pressure_high',
        severity: 'critical',
        status: '严重异常',
        descriptions: [
          '压力值超出安全范围',
          '压力值持续异常',
          '压力峰值超过阈值',
          '压力传感器读数异常'
        ]
      },
      {
        type: 'pressure_low',
        severity: 'warning',
        status: '轻微异常',
        descriptions: [
          '压力值略低于正常范围',
          '压力传感器信号弱',
          '压力值波动异常'
        ]
      },
      {
        type: 'device_offline',
        severity: 'critical',
        status: '设备离线',
        descriptions: [
          '设备通信中断',
          '设备电源故障',
          '网络连接异常',
          '设备硬件故障'
        ]
      },
      {
        type: 'battery_low',
        severity: 'warning',
        status: '电池电量低',
        descriptions: [
          '设备电池电量不足',
          '需要更换电池',
          '电池性能下降'
        ]
      },
      {
        type: 'temperature_high',
        severity: 'warning',
        status: '温度异常',
        descriptions: [
          '设备温度过高',
          '环境温度异常',
          '散热系统故障'
        ]
      }
    ]
    
    // 生成最近的异常事件
    const exceptionCount = Math.floor(Math.random() * 15) + 5 // 5-20个异常
    
    for (let i = 0; i < exceptionCount; i++) {
      const exceptionType = exceptionTypes[Math.floor(Math.random() * exceptionTypes.length)]
      const timeOffset = Math.random() * 24 * 60 * 60 * 1000 // 最近24小时内
      const exceptionTime = new Date(now.getTime() - timeOffset)
      
      // 生成位置
      const area = ['A', 'B', 'C'][Math.floor(Math.random() * 3)]
      const x = Math.floor(Math.random() * 10) + 1
      const y = Math.floor(Math.random() * 10) + 1
      const position = `区域${area}-${x}-${y}`
      
      // 生成压力值（根据异常类型）
      let pressure
      if (exceptionType.type === 'pressure_high') {
        pressure = (5.5 + Math.random() * 2.5).toFixed(2)
      } else if (exceptionType.type === 'pressure_low') {
        pressure = (0.5 + Math.random() * 1.5).toFixed(2)
      } else {
        pressure = (2.0 + Math.random() * 4.0).toFixed(2)
      }
      
      // 生成处理状态
      const processingStates = ['未处理', '处理中', '已处理', '已忽略']
      const processingWeights = [0.3, 0.2, 0.4, 0.1] // 权重
      let processingStatus = processingStates[0]
      const rand = Math.random()
      let cumWeight = 0
      for (let j = 0; j < processingStates.length; j++) {
        cumWeight += processingWeights[j]
        if (rand <= cumWeight) {
          processingStatus = processingStates[j]
          break
        }
      }
      
      exceptions.push({
        id: i + 1,
        time: exceptionTime.toLocaleString('zh-CN'),
        position,
        pressure,
        status: exceptionType.status,
        severity: exceptionType.severity,
        type: exceptionType.type,
        description: exceptionType.descriptions[Math.floor(Math.random() * exceptionType.descriptions.length)],
        deviceId: `TILE_${x.toString().padStart(2, '0')}_${y.toString().padStart(2, '0')}`,
        processingStatus,
        assignedTo: processingStatus !== '未处理' ? this.generateAssignee() : null,
        estimatedRepairTime: exceptionType.severity === 'critical' ? Math.floor(Math.random() * 4) + 1 : null,
        relatedAlerts: Math.floor(Math.random() * 3) + 1,
        impact: this.calculateImpact(exceptionType.severity),
        timestamp: exceptionTime.toISOString(),
        duration: this.calculateDuration(exceptionTime, processingStatus),
        rootCause: this.generateRootCause(exceptionType.type),
        resolution: processingStatus === '已处理' ? this.generateResolution(exceptionType.type) : null
      })
    }
    
    // 按时间排序（最新的在前）
    exceptions.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
    
    // 计算统计信息
    const stats = {
      total: exceptions.length,
      critical: exceptions.filter(e => e.severity === 'critical').length,
      warning: exceptions.filter(e => e.severity === 'warning').length,
      unprocessed: exceptions.filter(e => e.processingStatus === '未处理').length,
      processing: exceptions.filter(e => e.processingStatus === '处理中').length,
      resolved: exceptions.filter(e => e.processingStatus === '已处理').length,
      avgResolutionTime: this.calculateAvgResolutionTime(exceptions)
    }
    
    return {
      success: true,
      data: {
        list: exceptions.slice(0, 10), // 返回前10条
        statistics: stats,
        pagination: {
          current: 1,
          pageSize: 10,
          total: exceptions.length
        },
        filters: {
          severities: ['critical', 'warning'],
          areas: ['区域A', '区域B', '区域C'],
          statuses: ['未处理', '处理中', '已处理', '已忽略'],
          timeRanges: ['1小时内', '24小时内', '7天内', '30天内']
        },
        metadata: {
          updateTime: now.toISOString(),
          dataSource: 'realtime_monitoring',
          alertThresholds: {
            pressure_high: 5.5,
            pressure_low: 2.0,
            temperature_high: 35,
            battery_low: 20
          }
        }
      }
    }
  }

  /**
   * 生成动态健康评分
   * 基于多个因子计算系统整体健康状况
   */
  getMockHealthScore() {
    const now = new Date()
    
    // 计算各个健康因子
    const deviceOnlineScore = 85 + Math.random() * 15 // 85-100
    const pressureStabilityScore = 75 + Math.random() * 20 // 75-95
    const alertFrequencyScore = 80 + Math.random() * 15 // 80-95
    const networkQualityScore = 88 + Math.random() * 12 // 88-100
    const dataIntegrityScore = 90 + Math.random() * 10 // 90-100
    const energyEfficiencyScore = 70 + Math.random() * 25 // 70-95
    
    // 权重配置
    const factors = {
      deviceOnline: { 
        score: parseFloat(deviceOnlineScore.toFixed(1)), 
        weight: 0.25,
        description: '设备在线率',
        status: deviceOnlineScore > 90 ? 'excellent' : (deviceOnlineScore > 80 ? 'good' : 'poor')
      },
      pressureStability: { 
        score: parseFloat(pressureStabilityScore.toFixed(1)), 
        weight: 0.30,
        description: '压力稳定性',
        status: pressureStabilityScore > 85 ? 'excellent' : (pressureStabilityScore > 75 ? 'good' : 'poor')
      },
      alertFrequency: { 
        score: parseFloat(alertFrequencyScore.toFixed(1)), 
        weight: 0.20,
        description: '告警频率',
        status: alertFrequencyScore > 85 ? 'excellent' : (alertFrequencyScore > 75 ? 'good' : 'poor')
      },
      networkQuality: { 
        score: parseFloat(networkQualityScore.toFixed(1)), 
        weight: 0.10,
        description: '网络质量',
        status: networkQualityScore > 90 ? 'excellent' : (networkQualityScore > 80 ? 'good' : 'poor')
      },
      dataIntegrity: { 
        score: parseFloat(dataIntegrityScore.toFixed(1)), 
        weight: 0.10,
        description: '数据完整性',
        status: dataIntegrityScore > 95 ? 'excellent' : (dataIntegrityScore > 85 ? 'good' : 'poor')
      },
      energyEfficiency: { 
        score: parseFloat(energyEfficiencyScore.toFixed(1)), 
        weight: 0.05,
        description: '能耗效率',
        status: energyEfficiencyScore > 85 ? 'excellent' : (energyEfficiencyScore > 70 ? 'good' : 'poor')
      }
    }
    
    // 计算加权总分
    const totalScore = Object.values(factors).reduce((sum, factor) => {
      return sum + factor.score * factor.weight
    }, 0)
    
    // 确定健康等级
    let level = 'good'
    let levelDescription = '良好'
    if (totalScore >= 90) {
      level = 'excellent'
      levelDescription = '优秀'
    } else if (totalScore >= 80) {
      level = 'good'
      levelDescription = '良好'
    } else if (totalScore >= 70) {
      level = 'fair'
      levelDescription = '一般'
    } else {
      level = 'poor'
      levelDescription = '较差'
    }
    
    // 生成建议
    const recommendations = this.generateHealthRecommendations(factors, totalScore)
    
    // 生成历史趋势
    const healthHistory = this.generateHealthHistory()
    
    return {
      success: true,
      data: {
        score: Math.round(totalScore),
        level,
        levelDescription,
        factors,
        recommendations,
        trends: {
          score: healthHistory,
          improvement: this.calculateImprovement(healthHistory),
          prediction: this.predictHealthTrend(healthHistory)
        },
        alerts: this.generateHealthAlerts(factors),
        maintenance: {
          nextScheduled: this.generateNextMaintenance(),
          overdue: this.generateOverdueMaintenance(),
          recommendations: this.generateMaintenanceRecommendations(factors)
        },
        metadata: {
          updateTime: now.toISOString(),
          calculationMethod: 'weighted_average',
          dataQuality: '95%',
          lastCalibration: this.generateLastCalibration()
        }
      }
    }
  }

  // ========== 辅助方法 ==========

  /**
   * 生成运行时间
   */
  generateUptime() {
    const days = Math.floor(Math.random() * 100) + 50
    const hours = Math.floor(Math.random() * 24)
    const minutes = Math.floor(Math.random() * 60)
    return `${days}天${hours}小时${minutes}分钟`
  }

  /**
   * 生成网络延迟
   */
  generateNetworkLatency() {
    return parseFloat((15 + Math.random() * 25).toFixed(1)) + 'ms'
  }

  /**
   * 生成设备状态
   */
  generateDeviceStatus(pressure) {
    if (pressure > 5.5) return 'critical'
    if (pressure > 3.8) return 'warning'
    if (pressure < 1.5) return 'maintenance'
    return 'normal'
  }

  /**
   * 生成最后维护时间
   */
  generateLastMaintenance() {
    const days = Math.floor(Math.random() * 30) + 1
    const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
    return date.toLocaleDateString('zh-CN')
  }

  /**
   * 生成每小时事件
   */
  generateHourlyEvents(pressure, alerts) {
    const events = []
    if (alerts > 0) {
      events.push(`${alerts}个告警`)
    }
    if (pressure > 5.0) {
      events.push('高压力事件')
    }
    if (Math.random() < 0.1) {
      events.push('设备重启')
    }
    return events
  }

  /**
   * 分析趋势
   */
  analyzeTrend(hours) {
    const recent = hours.slice(-6) // 最近6小时
    const earlier = hours.slice(-12, -6) // 之前6小时
    
    const recentAvg = recent.reduce((sum, h) => sum + h.pressure, 0) / recent.length
    const earlierAvg = earlier.reduce((sum, h) => sum + h.pressure, 0) / earlier.length
    
    const change = ((recentAvg - earlierAvg) / earlierAvg * 100).toFixed(1)
    
    return {
      direction: recentAvg > earlierAvg ? 'increasing' : 'decreasing',
      change: `${Math.abs(change)}%`,
      description: recentAvg > earlierAvg ? '压力呈上升趋势' : '压力呈下降趋势'
    }
  }

  /**
   * 生成建议
   */
  generateRecommendations(summary) {
    const recommendations = []
    
    if (summary.totalAlerts > 20) {
      recommendations.push('告警数量较多，建议检查系统配置')
    }
    if (summary.avgPressure > 4.0) {
      recommendations.push('平均压力偏高，建议优化负载分布')
    }
    if (summary.avgResponseTime > 100) {
      recommendations.push('响应时间较长，建议检查网络状况')
    }
    
    if (recommendations.length === 0) {
      recommendations.push('系统运行良好，保持当前状态')
    }
    
    return recommendations
  }

  /**
   * 生成预测
   */
  generateForecast(hours) {
    const trend = this.analyzeTrend(hours)
    const nextHour = hours[hours.length - 1].pressure
    
    let forecast = nextHour
    if (trend.direction === 'increasing') {
      forecast += 0.2 + Math.random() * 0.3
    } else {
      forecast -= 0.2 + Math.random() * 0.3
    }
    
    return {
      nextHour: parseFloat(Math.max(1.0, Math.min(6.0, forecast)).toFixed(1)),
      confidence: parseFloat((75 + Math.random() * 20).toFixed(1)),
      trend: trend.direction
    }
  }

  /**
   * 生成最后事故时间
   */
  generateLastIncident() {
    const days = Math.floor(Math.random() * 15) + 1
    const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
    return date.toLocaleDateString('zh-CN')
  }

  /**
   * 生成维护计划
   */
  generateMaintenanceSchedule() {
    const days = Math.floor(Math.random() * 7) + 1
    const date = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
    return date.toLocaleDateString('zh-CN')
  }

  /**
   * 生成区域趋势
   */
  generateAreaTrend() {
    return {
      direction: Math.random() > 0.5 ? 'up' : 'down',
      change: parseFloat((Math.random() * 10).toFixed(1))
    }
  }

  /**
   * 生成区域建议
   */
  generateAreaRecommendations(areas) {
    const recommendations = []
    
    areas.forEach(area => {
      if (area.critical > 5) {
        recommendations.push(`${area.area}严重异常较多，需要紧急处理`)
      }
      if (area.efficiency < 70) {
        recommendations.push(`${area.area}效率偏低，建议优化配置`)
      }
    })
    
    if (recommendations.length === 0) {
      recommendations.push('各区域运行状况良好')
    }
    
    return recommendations
  }

  /**
   * 生成负责人
   */
  generateAssignee() {
    const assignees = ['张工程师', '李技术员', '王维护员', '赵操作员', '陈主管']
    return assignees[Math.floor(Math.random() * assignees.length)]
  }

  /**
   * 计算影响程度
   */
  calculateImpact(severity) {
    const impacts = {
      critical: ['高', '严重', '极高'],
      warning: ['中', '轻微', '低']
    }
    const options = impacts[severity] || impacts.warning
    return options[Math.floor(Math.random() * options.length)]
  }

  /**
   * 计算持续时间
   */
  calculateDuration(startTime, status) {
    if (status === '未处理') {
      const now = new Date()
      const duration = now - new Date(startTime)
      const hours = Math.floor(duration / (1000 * 60 * 60))
      const minutes = Math.floor((duration % (1000 * 60 * 60)) / (1000 * 60))
      return `${hours}小时${minutes}分钟`
    }
    
    const hours = Math.floor(Math.random() * 8) + 1
    const minutes = Math.floor(Math.random() * 60)
    return `${hours}小时${minutes}分钟`
  }

  /**
   * 生成根本原因
   */
  generateRootCause(type) {
    const causes = {
      pressure_high: ['负载过重', '传感器故障', '系统配置错误', '环境因素'],
      pressure_low: ['传感器故障', '连接松动', '电源问题', '校准偏差'],
      device_offline: ['网络故障', '电源故障', '硬件故障', '软件异常'],
      battery_low: ['电池老化', '充电系统故障', '功耗异常', '环境温度'],
      temperature_high: ['散热不良', '环境温度高', '设备老化', '负载过重']
    }
    
    const options = causes[type] || ['未知原因']
    return options[Math.floor(Math.random() * options.length)]
  }

  /**
   * 生成解决方案
   */
  generateResolution(type) {
    const resolutions = {
      pressure_high: ['调整系统参数', '更换传感器', '重新校准', '优化负载'],
      pressure_low: ['检查连接', '更换传感器', '重新校准', '检查电源'],
      device_offline: ['重启设备', '检查网络', '更换硬件', '更新软件'],
      battery_low: ['更换电池', '检查充电系统', '优化功耗', '改善环境'],
      temperature_high: ['改善散热', '降低环境温度', '更换设备', '减少负载']
    }
    
    const options = resolutions[type] || ['联系技术支持']
    return options[Math.floor(Math.random() * options.length)]
  }

  /**
   * 计算平均解决时间
   */
  calculateAvgResolutionTime(exceptions) {
    const resolved = exceptions.filter(e => e.processingStatus === '已处理')
    if (resolved.length === 0) return '暂无数据'
    
    const avgHours = 2 + Math.random() * 4 // 2-6小时
    return `${avgHours.toFixed(1)}小时`
  }

  /**
   * 生成健康建议
   */
  generateHealthRecommendations(factors, totalScore) {
    const recommendations = []
    
    Object.entries(factors).forEach(([key, factor]) => {
      if (factor.score < 80) {
        switch (key) {
          case 'deviceOnline':
            recommendations.push('部分设备离线，建议检查网络连接和设备状态')
            break
          case 'pressureStability':
            recommendations.push('压力波动较大，建议检查传感器校准和系统负载')
            break
          case 'alertFrequency':
            recommendations.push('告警频率偏高，建议优化阈值设置和预防性维护')
            break
          case 'networkQuality':
            recommendations.push('网络质量需要改善，建议检查网络设备和带宽')
            break
          case 'dataIntegrity':
            recommendations.push('数据完整性有待提升，建议检查数据采集和传输')
            break
          case 'energyEfficiency':
            recommendations.push('能耗效率可以优化，建议调整设备工作模式')
            break
        }
      }
    })
    
    if (totalScore >= 90) {
      recommendations.push('系统运行优秀，保持当前维护策略')
    } else if (totalScore >= 80) {
      recommendations.push('系统运行良好，建议定期检查和预防性维护')
    } else {
      recommendations.push('系统需要关注，建议制定改进计划')
    }
    
    return recommendations
  }

  /**
   * 生成健康历史
   */
  generateHealthHistory() {
    const history = []
    for (let i = 6; i >= 0; i--) {
      const date = new Date(Date.now() - i * 24 * 60 * 60 * 1000)
      const score = 75 + Math.random() * 20 + Math.sin(i * 0.5) * 5
      history.push({
        date: date.toLocaleDateString('zh-CN'),
        score: Math.round(Math.max(60, Math.min(100, score)))
      })
    }
    return history
  }

  /**
   * 计算改善情况
   */
  calculateImprovement(history) {
    if (history.length < 2) return 0
    const latest = history[history.length - 1].score
    const previous = history[history.length - 2].score
    return parseFloat(((latest - previous) / previous * 100).toFixed(1))
  }

  /**
   * 预测健康趋势
   */
  predictHealthTrend(history) {
    if (history.length < 3) return { trend: 'stable', confidence: 50 }
    
    const recent = history.slice(-3).map(h => h.score)
    const trend = recent[2] > recent[0] ? 'improving' : (recent[2] < recent[0] ? 'declining' : 'stable')
    const confidence = 70 + Math.random() * 25
    
    return {
      trend,
      confidence: parseFloat(confidence.toFixed(1)),
      description: trend === 'improving' ? '健康状况正在改善' : 
                  (trend === 'declining' ? '健康状况有所下降' : '健康状况保持稳定')
    }
  }

  /**
   * 生成健康告警
   */
  generateHealthAlerts(factors) {
    const alerts = []
    
    Object.entries(factors).forEach(([, factor]) => {
      if (factor.score < 70) {
        alerts.push({
          type: 'warning',
          message: `${factor.description}评分偏低 (${factor.score}分)`,
          recommendation: `建议关注${factor.description}相关指标`
        })
      }
    })
    
    return alerts
  }

  /**
   * 生成下次维护时间
   */
  generateNextMaintenance() {
    const days = Math.floor(Math.random() * 14) + 1
    const date = new Date(Date.now() + days * 24 * 60 * 60 * 1000)
    return date.toLocaleDateString('zh-CN')
  }

  /**
   * 生成过期维护
   */
  generateOverdueMaintenance() {
    if (Math.random() < 0.3) { // 30%概率有过期维护
      const days = Math.floor(Math.random() * 7) + 1
      const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
      return {
        task: '传感器校准',
        dueDate: date.toLocaleDateString('zh-CN'),
        overdueDays: days
      }
    }
    return null
  }

  /**
   * 生成维护建议
   */
  generateMaintenanceRecommendations(factors) {
    const recommendations = []
    
    if (factors.deviceOnline.score < 85) {
      recommendations.push('检查离线设备并进行维修')
    }
    if (factors.pressureStability.score < 80) {
      recommendations.push('校准压力传感器')
    }
    if (factors.networkQuality.score < 85) {
      recommendations.push('检查网络设备和连接')
    }
    
    recommendations.push('定期清洁设备和检查连接')
    recommendations.push('更新设备固件到最新版本')
    
    return recommendations
  }

  /**
   * 生成最后校准时间
   */
  generateLastCalibration() {
    const days = Math.floor(Math.random() * 90) + 30
    const date = new Date(Date.now() - days * 24 * 60 * 60 * 1000)
    return date.toLocaleDateString('zh-CN')
  }
}

// 创建单例实例
const smartTileApi = new SmartTileApiService()

export default smartTileApi
